<template>
  <div class="container">
    <div class="mb10">
      <el-text class="mx-1"> 查询条件：</el-text>
    </div>
    <el-row :gutter="10">
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-input v-model.trim="searchCondition.name" placeholder="分类名称" clearable></el-input>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-space wrap>
          <el-button type="success" :icon="Search" :disabled="disabledbtn" @click="searchInfo">搜索</el-button>
          <el-button type="warning" :icon="Refresh" :disabled="disabledbtn" @click="resetSearch">重置</el-button>
        </el-space>
      </el-col>
    </el-row>
    <div class="mb10">
      <el-text class="mx-1"> 查询结果：</el-text>
    </div>
    <el-space wrap class="mb20">
      <el-button type="primary" :icon="Plus" :disabled="disabledbtn" @click="changeFormStatus('add')" v-permission="'add'">新增</el-button>
      <el-popconfirm placement="top" width="160" title="你确定要删除吗?" @confirm="batchDelete">
        <template #reference>
          <el-button type="danger" :icon="Delete" :disabled="disabledbtn">批量删除</el-button>
        </template>
      </el-popconfirm>
    </el-space>

    <el-table :data="tableList.slice((pageNumber - 1) * pageSize, pageNumber * pageSize)" border class="table" row-key="id" ref="multipleTableRef" v-loading="loading" :reserve-selection="true" @row-dblclick="rowDblclick">
      <el-table-column type="index" align="center"> </el-table-column>
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="name" label="客服分类名称" align="center"> </el-table-column>
      <el-table-column prop="start_time" label="在线时间" align="center" :formatter="handlFormatterTime"> </el-table-column>
      <el-table-column prop="sort" label="排序" align="center">
        <template #default="scope">
          <div class="">
            <el-input v-model.trim.number="scope.row.sort" placeholder="请输入内容" @change="handleSort(scope.row)"></el-input>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="190" align="center">
        <template #default="scope">
          <div class="control-flex">
            <el-button type="primary" link :icon="View" @click="handleViewEdit(scope.row, 'view', '查看')">查看</el-button>
            <el-button type="primary" link :icon="EditPen" v-permission="'edit'" @click="handleViewEdit(scope.row, 'edit', '编辑')">编辑</el-button>
            <div v-permission="'delete'">
              <el-popconfirm placement="top" width="160" title="你确定要删除吗?" @confirm="deleteInfo([scope.row.id])">
                <template #reference>
                  <el-button link :icon="Delete" type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        @update:current-page="handleCurrentChange"
        @update:page-size="handleSizeChange"
        layout="total, sizes, prev, pager, next, jumper"
        :page-size="pageSize"
        :current-page="pageNumber"
        :page-sizes="[10, 20, 30, 40, 50, 100]"
        :total="total"
        :hide-on-single-page="false">
      </el-pagination>
    </div>
  </div>
</template>

<script setup lang="ts">
import { View, Delete, EditPen, Search, Plus, Refresh } from "@element-plus/icons-vue";
import { handleVerifyFormatHMSDate } from "@/utils/utils";

import type { ISort, ViewMode, ViewModeFilter } from "@/types/common";
import type { ICustomer, ISearchCustomer } from "@/types/customerServicClass";
import { deleteCustomerServiceCategoryInfo, getCustomerServiceCategoryInfo, putCustomerServiceCategorySortInfo } from "@/utils/api/customerServiceCategory";
import { useState } from "@/hooks/useState.ts";
const { disabledbtn, loading, toggleState } = useState();

const formStatus = defineModel<ViewMode>("formStatus", { required: true });

const emit = defineEmits<{
  handleViewEdit: [row: ICustomer, code: ViewModeFilter, name: string];
}>();
/* 暴露一个方法给父组件使用 */
defineExpose({
  getTableInfo
});

const multipleTableRef = useTemplateRef("multipleTableRef"); /* 列表组件的引用 */
const total = ref(0);
const pageNumber = ref(1);
const pageSize = ref(10);
const searchCondition = reactive<ISearchCustomer>({
  name: ""
});
const tableList = ref<Array<ICustomer>>([]);

onMounted(() => {
  getTableInfo();
});
/* 搜索 */
function searchInfo() {
  pageNumber.value = 1;
  pageSize.value = 10;
  getTableInfo();
}

/**
 * 重置搜索内容
 */
function resetSearch() {
  searchCondition.name = "";
  searchInfo();
}
/* 格式化是否显示 */
function handlFormatterTime(row: ICustomer) {
  return `${handleVerifyFormatHMSDate(row.start_time)} -- ${handleVerifyFormatHMSDate(row.end_time)}`;
}
/* 处理排序 */
function handleSort({ id, sort }: ISort) {
  if (typeof sort !== "number") {
    ElMessage.warning("请输入数字");
    return;
  }
  putCustomerServiceCategorySortInfo({ id, sort })
    .then(() => {
      ElMessage.success("修改成功");
      getTableInfo();
    })
    .catch(() => {});
}

/**
 * 切换表单状态（ 添加、编辑、查看 ，隐藏none ）
 */
function changeFormStatus(state: ViewMode) {
  formStatus.value = state;
}

/* 请求：获取表格中数据 */
function getTableInfo() {
  toggleState(true);
  getCustomerServiceCategoryInfo<Array<ICustomer>, ISearchCustomer>(searchCondition)
    .then(res => {
      tableList.value = res.result;
      total.value = tableList.value.length;
    })
    .finally(() => {
      toggleState(false);
    });
}

/* 显示第几页 */
function handleCurrentChange(val: number) {
  pageNumber.value = val;
}

/* 每页显示几条 */
function handleSizeChange(val: number) {
  pageSize.value = val;
}

/* 触发处理 查看编辑事件 */
function handleViewEdit(row: ICustomer, code: ViewModeFilter, name: string) {
  emit("handleViewEdit", row, code, name);
}

/* 双击当前行 */
function rowDblclick(row: ICustomer) {
  multipleTableRef.value!.toggleRowSelection(row);
}

/* 批量删除 */
function batchDelete() {
  /* 获取选中的数据 */
  let selection = multipleTableRef.value!.store.states.selection.value;
  if (selection.length === 0) {
    ElMessage.warning("请至少选择一条数据");
    return;
  }
  let idArray = [];
  for (const item of selection) {
    idArray.push(item.id);
  }
  deleteInfo(idArray);
}
/* 删除后的信息 */
function deleteInfo(idArray: Array<number>) {
  toggleState(true);
  deleteCustomerServiceCategoryInfo({ idArray })
    .then(() => {
      /* 当删除成功后，删除对应选中的数据或单个数据 */
      tableList.value = tableList.value.filter((item: ICustomer) => !idArray.includes(item.id));
      ElMessage.success(`成功删除了${idArray.length}条数据`);
      multipleTableRef.value!.clearSelection();
      total.value = total.value - idArray.length;
    })
    .catch((error: Error) => {
      console.log(error);
    })
    .finally(() => {
      toggleState(false);
    });
}
</script>

<style lang="scss" scoped>
/* layout-布局 */
.el-col {
  border-radius: 4px;
}

.mb10 {
  margin-bottom: 10px;
}
/* 关键：列表右侧操作按钮的对其 */
:deep(.el-space__item) {
  line-height: 15px;
}

.el-button.is-text + .el-button.is-text {
  margin-left: 0;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.del-dialog-cnt {
  font-size: 16px;
  text-align: center;
}

.table {
  width: 100%;
  font-size: 14px;
}
.textAlignCenter {
  text-align: center;
}

/* 确定按钮的显示与隐藏 */
.displaybtn {
  display: none;
}

/* 提示图标设置 */
.icon-wzg-config {
  height: 30px;
  line-height: 30px;
}

/* 修改Switch开关 */
.el-switch {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
</style>
